﻿IF OBJECT_ID('[finance].[fn_ExistsBankkontoByKontoname]') IS NOT NULL
BEGIN
	DROP FUNCTION [finance].[fn_ExistsBankkontoByKontoname]
END
GO
CREATE FUNCTION [finance].[fn_ExistsBankkontoByKontoname]
(
	@Kontoname NVARCHAR(256)
)
RETURNS BIT
AS
BEGIN
	DECLARE @returnValue BIT
	SELECT @returnValue = COUNT(1) FROM [finance].[Bankkonto]
		WHERE Kontoname = @Kontoname
	RETURN @returnValue
END
GO

IF OBJECT_ID('[finance].[AddBankkonto]') IS NOT NULL
BEGIN
	DROP PROCEDURE [finance].[AddBankkonto]
END

GO
CREATE PROCEDURE [finance].[AddBankkonto]
	@Kontonummer		NVARCHAR(50),
	@Bankleitzahl		NVARCHAR(50),
	@Bankname			NVARCHAR(256),
	@Kontoname			NVARCHAR(256),
	@IBAN				NVARCHAR(50) = NULL,
	@CreatedBy			NVARCHAR(256),
	@CreatedFromSource	NVARCHAR(256),
	@VersionNumber		VARCHAR(25),
	@SessionID			VARCHAR(50),
	@LanguageID			INT
AS
BEGIN
	DECLARE
		@CreatedAt DATETIME = GETDATE(),
		@errorReturn INT = 0

	-- Kontonummer prüfen
	EXEC @errorReturn = [core].[ValidateStringParameter] @Kontonummer, 0, 0, 0, 50, 'finance', 'Bankkonto', 1, @VersionNumber, @SessionID, @LanguageID;

	IF @errorReturn <> 0
	BEGIN
		RETURN @errorReturn;
	END
	
	-- Bankleitzahl prüfen
	EXEC @errorReturn = [core].[ValidateStringParameter] @Bankleitzahl, 0, 0, 0, 50, 'finance', 'Bankkonto', 1, @VersionNumber, @SessionID, @LanguageID;

	IF @errorReturn <> 0
	BEGIN
		RETURN @errorReturn;
	END

	-- Bankname prüfen
	EXEC @errorReturn = [core].[ValidateStringParameter] @Bankname, 0, 0, 0, 256, 'finance', 'Bankkonto', 1, @VersionNumber, @SessionID, @LanguageID;

	IF @errorReturn <> 0
	BEGIN
		RETURN @errorReturn;
	END

	-- Kontoname prüfen
	EXEC @errorReturn = [core].[ValidateStringParameter] @Bankname, 0, 0, 0, 256, 'finance', 'Bankkonto', 1, @VersionNumber, @SessionID, @LanguageID;

	IF @errorReturn <> 0
	BEGIN
		RETURN @errorReturn;
	END
	
	IF [finance].[fn_ExistsBankkontoByKontoname](@Kontoname) = 1
	BEGIN
		EXEC [core].[SaveLogging] GETDATE, 3, @VersionNumber, @CreatedBy, @CreatedFromSource, 10000, @LanguageID, @SessionID;
		RETURN 10000;
	END
END 